<?php
namespace app\home\controller;
use \think\Cookie;
use think\Db;
use \think\View;
use \think\Model;
use \think\Request;
use \GatewayClient\Gateway;
class User extends Model
{
    protected $resultSetType = 'collection';
}
class File extends Model
{
    protected $resultSetType = 'collection';
    protected $createTime = 'creat_time';
    protected $updateTime = false;
}
class StatusData extends Model
{
    protected $resultSetType = 'collection';
    protected $createTime = 'time';
    protected $updateTime = false;
}

class Filepage extends \think\Controller
{
    function create_floder($floder)
    {
        $cookie = Cookie::get('safecode');
        $user = User::getBySafecode($cookie)->toArray();
        $dir = $user['lastdir'];
        $floder1 = $dir . $floder;
        if (!file_exists($floder1)) {
            $make_dir = new File([
                'name' => $floder,
                'url' => $floder1,
                'type' => 'floder',
                'upper' => $dir
            ]);
            if ($make_dir->save()) {
                mkdir($floder1, 0777, true);
                $this->success('创建成功，正在跳转', 'file', '', 1);
            }
        } else {
            $this->error('存在此目录', '', '', 1);
        }
    }

    function getDir($path)
    {
        //判断目录是否为空
        if (!file_exists($path)) {
            return [];
        }

        $files = scandir($path);
        $fileItem = [];
        foreach ($files as $v) {
            $newPath = $v;
            if ($newPath != '.' && $newPath != '..')
                $fileItem[] = $newPath;

        }

        return $fileItem;
    }

    public function file()
    {
        $status = new StatusData();
        $person = new User();//获取当前用户信息
        $cookie = Cookie::get('safecode');
        $person_data = User::getBySafecode($cookie);
        ////获取当前所在路径
        if (input('get.dir')) {
            $dir = input('get.dir') . '/';
        } else {
            $dir = 'file/' . $person_data['dir'] . '/';
        }

        if (input('post.floder')) {
            $floder = input('post.floder');
            $this->create_floder($floder);
            $status->insert(['msg' => '创建了新的文件夹' . $floder, 'uid' => $person_data['Id'], 'time' => date('Y-m-d H:i:s', time())]);

        }
        ////获取当前域名
        $request = Request::instance();//获取域名
        $domain = $request->domain();
        ///
        $person->where('safecode', $cookie)->update(['lastdir' => $dir]);
        ///判断是否有空间
        if (!$person_data['dir']) {
            $this->success("您是老用户，正在为您跳转到空间申请页哦", "apply");
        }
        //$file_arr=$this->getDir('file/'.$person_data['dir']);//获取当前文件夹下东西
        //$dir='file/'.$person_data['dir'].'/'.$cur_dir;
        $file_list = new File();
        $file_arr = $file_list->where('type', '<>', 'floder')->where('url', $dir)->select()->toArray();
        $floder = $file_list->where('upper', $dir)->where('type', 'floder')->select()->toArray();
        $cur_dir = File::getByUrl(input('get.dir'));
        $upper = substr($cur_dir["upper"], 0, strlen($cur_dir["upper"]) - 1);
        if (input('post.del')) {//是否有要删除的文件
            $input = input('post.del');//获取要删除的文件名
            $del_file = $dir . $input;
            if (unlink($del_file)) {
                $this->success("删除成功");
            }
        }

        $view = new View();
        $view->assign('desc', $cur_dir['description']);
        $view->assign('upper', $upper);
        $view->assign('floder', $floder);
        //$view->assign('dir',$dir);
        $view->assign('dir', input('get.dir'));
        $view->assign('domain', $domain);
        $view->assign('file', $file_arr);
        return $view->fetch('file', [], ['__PUBLIC__' => '/public/static']);
    }

    public function apply()
    {
        $view = new View();
        $random = random(20, 'all');
        $cookie = Cookie::get('safecode');
        if (!mkdir('file/' . $random, 0777)) {
            $this->error('出了点小问题');
            exit();
        }
        $person_up = User::where('safecode', $cookie)->update(['dir' => $random]);
        if ($person_up) {
            $view->assign('msg', '<div class="alert alert-success">
                            处理成功<br>
                            您可以愉快得使用此功能了
                        </div>');

        } else {
            $view->assign('msg', '<div class="alert alert-danger">
                            处理失败
                        </div>');
        }
        return $view->fetch('apply', [], ['__PUBLIC__' => '/public/static']);
    }

    public function upload_file()   //
    {
        $view = new View();
        return $view->fetch('upload', [], ['__PUBLIC__' => '/public/static']);
    }

    public function upload()
    {//上传文件
        //{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}
        //print_r('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}');
        $cookie = Cookie::get('safecode');
        $status = new StatusData();
        $person_data = User::getBySafecode($cookie);
        $dir = $person_data['lastdir'];
        $allowedExts = array("php", "exe", "bat", "sh");
        $temp = explode(".", $_FILES["file"]["name"]);

        $extension = end($temp);        // 获取文件后缀名
        if (in_array($extension, $allowedExts)) {
            echo '{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "invalid type."}, "id" : "id"}';
            exit();
        }
        if (($_FILES["file"]["size"] < 524288000)    // 小于 500 mb
            && !in_array($extension, $allowedExts)) {
            if ($_FILES["file"]["error"] > 0) {
                echo '{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}';
            } else {
                if (file_exists($dir . $_FILES["file"]["name"])) {
                    echo '{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "文件存在"}, "id" : "id"}';
                } else {
                    // 如果 upload 目录不存在该文件则将文件上传到 upload 目录下

                    $name = $_FILES["file"]["name"];
                    $upper = $person_data["lastdir"];
                    $url = $dir;
                    $type = $extension;
                    $file = new File([
                        'name' => $name,
                        'upper' => $url,
                        'url' => $url,
                        'type' => $type
                    ]);

                    if ($file->save()) {
                        move_uploaded_file($_FILES["file"]["tmp_name"], $dir . $_FILES["file"]["name"]);
                        $status->insert(['msg' => '上传了文件' . $_FILES["file"]["name"], 'uid' => $person_data['Id'], 'time' => date('Y-m-d H:i:s', time())]);
                    } else {
                        echo '{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "文件存在"}, "id" : "id"}';
                    }

                    echo '{"jsonrpc" : "2.0", "result" : null, "id" : "id"}';
                }

            }
        } else {
            echo '{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "文件格式非法."}, "id" : "id"}';
        }

    }
}